const app = getApp();
var Wxmlify = require('../../wxmlify/wxmlify.js');

// pages/detail/audio/detail.js
let backgroundAudioManager = wx.getBackgroundAudioManager();

Page({
  data: {
    poster: null,
    courseId: null,
    courseDetail: null,

    nodes: null,
    playOrPause: "播放",
    sliderValue: 0,
    title: null,

    currentTime: "00:00:00",
    endTime: "23:59:59",
    max: 100,
    stopOnTimeUpdate: true
  },

  secondToDateTime(result) {
    var h = Math.floor(result / 3600);
    if (h.toString().length < 2)
      h = "0" + h;
    var m = Math.floor((result / 60 % 60));
    if (m.toString().length < 2)
      m = "0" + m;
    var s = Math.floor((result % 60));
    if (s.toString().length < 2)
      s = "0" + s;

    return result = h + ":" + m + ":" + s;
  },

  audioPlay: function () {
    if (backgroundAudioManager.paused == undefined || backgroundAudioManager.paused) {
      backgroundAudioManager.title = this.data.title;
      backgroundAudioManager.coverImgUrl = this.data.poster;
      backgroundAudioManager.src = this.data.courseDetail.resourceUrl;

      wx.getStorage({
        key: "position_" + this.data.courseDetail.id,
        success: function (res) {
          if (res.data > 0) {
            wx.stopBackgroundAudio();
            let position = res.data;

            wx.showModal({
              title: '提示',
              content: '找到上次播放记录，是否跳转？',
              success: function (res) {
                if (res.cancel) {
                  //点击取消,默认隐藏弹框
                  backgroundAudioManager.play();
                } else {
                  //点击确定
                  backgroundAudioManager.seek(position);
                  backgroundAudioManager.play();
                }
              },
              fail: function (res) { },//接口调用失败的回调函数
              complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
            });            
          }
        }
      });

      backgroundAudioManager.play();
      this.setData({
        stopOnTimeUpdate: false
      });

      wx.setStorage({
        key: 'currentPlay',
        data: "position_" + this.data.courseDetail.id,
      });

    } else {
      this.setData({
        playOrPause: '暂停'
      });
      backgroundAudioManager.pause();

    }

  },

  onLoad: function (options) {
    var that = this;
    console.log(options);

    wx.request({
      url: app.globalData.serverUrl + '/courseDetail/getCourseDetailById',
      data: {
        id: options.id
      },
      success(resp) {
        if (resp.data.success) {
          that.setData({
            courseDetail: resp.data.data,
            // nodes: JSON.parse(resp.data.data.detail),
            title: resp.data.data.name,
            poster: options.poster
          });

          let html = that.data.courseDetail.detail;
          if (html == null)
            html = "";
          var wxmlify = new Wxmlify(html, that, {});

          // 更新进度条
          backgroundAudioManager.onTimeUpdate(() => {
            wx.getStorage({
              key: 'currentPlay',
              success: function (res) {
                if (res.data != "position_" + that.data.courseDetail.id)
                  that.setData({
                    stopOnTimeUpdate: false
                  });
              },
            });

            if (that.data.stopOnTimeUpdate) {
              that.setData({
                sliderValue: 0,
                max: 100,
                endTime: "23:59:59",
                currentTime: "00:00:00",
                playOrPause: "播放"
              });

              return;
            }

            if (!backgroundAudioManager.paused) {
              that.setData({
                sliderValue: backgroundAudioManager.currentTime,
                max: backgroundAudioManager.duration,
                endTime: that.secondToDateTime(backgroundAudioManager.duration),
                currentTime: that.secondToDateTime(backgroundAudioManager.currentTime),
                playOrPause: "播放中"
              });

              wx.setStorage({
                key: "position_" + resp.data.data.id,
                data: backgroundAudioManager.currentTime
              });

            } else {
              that.setData({
                playOrPause: "暂停"
              });
            }
          });

          backgroundAudioManager.onWaiting(() => {
            console.log("加载数据中...");
            that.setData({
              playOrPause: "加载数据中..."
            });
          });

        }
      }
    });

    /*
    var timer = setInterval(() => {
      wx.getBackgroundAudioPlayerState({
        success: function (res) {
          console.log(res);
          if (res.status == 1) {
            that.setData({
              sliderValue: res.currentPosition
            });

            wx.setStorage({
              key: "currentPosition",
              data: res.currentPosition
            })
          }
        }
      });
    }, 1000);
    */



  },

  bindtouchstart(e) {
    console.log("暂停");
    backgroundAudioManager.pause();
  },

  slider3change(e) {
    console.log("slider3change: " + e.detail.value);

    this.setData({
      sliderValue: e.detail.value,
      currentTime: this.secondToDateTime(e.detail.value)
    });

    backgroundAudioManager.seek(e.detail.value);
  },

  bindtouchend(e) {
    console.log("继续播放");
    backgroundAudioManager.play();
  },

  test(e) {
    console.log(e);
    backgroundAudioManager.seek(1000);
    backgroundAudioManager.play();
  }

})